<?php
session_start();
if (!isset($_SESSION['user'])) {
    header('Location: index.php');
    exit;
}

$pageTitle = "编辑文章";
include 'includes/functions.php';

// 获取文章ID
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$article = getArticleById($id);

if (!$article) {
    header('Location: index.php');
    exit;
}

// 检查是否为文章作者
if (!isArticleOwner($id, $_SESSION['user']['user_id'])) {
    header('Location: home.php');
    exit;
}

include 'includes/header.php';
?>

<div class="container">
    <div class="form-container">
        <h2>编辑文章</h2>
        <form id="edit-article-form">
            <input type="hidden" id="edit-article-id" value="<?php echo $article['post_id']; ?>">
            
            <div class="form-group">
                <label for="edit-article-title">文章标题</label>
                <input type="text" id="edit-article-title" placeholder="请输入文章标题" required value="<?php echo htmlspecialchars($article['title']); ?>">
            </div>
            
            <div class="form-group">
                <label for="edit-article-categories">文章分类</label>
                <select id="edit-article-categories" required>
                    <option value="">请选择分类</option>
                    <!-- 分类选项将通过JavaScript动态加载 -->
                </select>
            </div>
            
            <div class="form-group">
                <label for="edit-article-content">文章内容</label>
                <textarea id="edit-article-content" placeholder="在此输入文章内容..." required rows="15"><?php echo htmlspecialchars($article['content']); ?></textarea>
            </div>
            
            <div class="form-group">
                <label for="edit-article-status">发布状态</label>
                <select id="edit-article-status">
                    <option value="published" <?php echo $article['status'] === 'published' ? 'selected' : ''; ?>>已发布</option>
                    <option value="draft" <?php echo $article['status'] === 'draft' ? 'selected' : ''; ?>>草稿</option>
                </select>
            </div>
            
            <div style="text-align: center; margin-top: 30px;">
                <button type="submit" class="btn btn-primary">更新文章</button>
                <a href="detail.php?id=<?php echo $article['post_id']; ?>" class="btn btn-accent">取消</a>
            </div>
        </form>
    </div>
</div>

<script>
let categories = [];
let articleCategory = null;

// 页面加载时获取分类列表和文章分类
document.addEventListener('DOMContentLoaded', function() {
    loadCategories();
    loadArticleCategory();
});

// 加载分类列表
function loadCategories() {
    fetch('api.php?action=get_categories')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                categories = data.data;
                renderEditCategoryOptions();
            } else {
                console.error('加载分类失败：', data.error);
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
}

// 加载文章分类
function loadArticleCategory() {
    const postId = document.getElementById('edit-article-id').value;
    fetch(`api.php?action=get_article_categories&post_id=${postId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data.length > 0) {
                articleCategory = data.data[0]; // 只取第一个分类
                renderEditCategoryOptions();
            } else {
                console.error('加载文章分类失败：', data.error);
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
}

// 渲染分类选项
function renderEditCategoryOptions() {
    const select = document.getElementById('edit-article-categories');
    
    if (categories.length === 0) {
        select.innerHTML = '<option value="">暂无分类，<a href="categories.php">去创建分类</a></option>';
        return;
    }
    
    // 保留默认选项
    select.innerHTML = '<option value="">请选择分类</option>';
    
    // 添加分类选项
    categories.forEach(category => {
        const option = document.createElement('option');
        option.value = category.category_id;
        option.textContent = category.name;
        if (articleCategory && articleCategory.category_id == category.category_id) {
            option.selected = true;
        }
        select.appendChild(option);
    });
}

document.getElementById('edit-article-form').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const postId = document.getElementById('edit-article-id').value;
    const title = document.getElementById('edit-article-title').value.trim();
    const content = document.getElementById('edit-article-content').value.trim();
    const status = document.getElementById('edit-article-status').value;
    const categoryId = document.getElementById('edit-article-categories').value;
    
    if (!title || !content) {
        alert('请填写标题和内容');
        return;
    }
    
    if (!categoryId) {
        alert('请选择分类');
        return;
    }
    
    const formData = new FormData();
    formData.append('action', 'update_article');
    formData.append('post_id', postId);
    formData.append('title', title);
    formData.append('content', content);
    formData.append('status', status);
    formData.append('category_id', categoryId);
    
    fetch('api.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            window.location.href = 'detail.php?id=' + postId;
        } else {
            alert(data.error || '更新失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('更新失败，请重试');
    });
});
</script>

<?php include 'includes/footer.php'; ?>